package cn.zxf.note.note.parse;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 解析月记
 * <p>
 * Created by zengxf on 2019-06-19
 */
@Slf4j
public class ParseMonthNote {

    private String file;
    private String content;

    public static ParseMonthNote of(String file) {
        ParseMonthNote parser = new ParseMonthNote();
        parser.file = file;
        return parser;
    }

    public MonthNoteVo parse() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(this.file), StandardCharsets.UTF_8));
        return this.parse(br);
    }

    public static ParseMonthNote ofContent(String content) {
        ParseMonthNote parser = new ParseMonthNote();
        parser.content = content;
        return parser;
    }

    public MonthNoteVo parseContent() throws IOException {
        Reader inputString = new StringReader(this.content);
        try (BufferedReader br = new BufferedReader(inputString)) {
            return this.parse(br);
        }
    }

    public MonthNoteVo parse(BufferedReader br) throws IOException {
        String line;
        int i = 0;
        boolean day = false;
        List<DayNoteVo> dayNotes = new ArrayList<>();
        String month = null;
        List<String> list = new ArrayList<>();
        while ((line = br.readLine()) != null) {
            if (i++ == 0) {
                if (line.startsWith("# "))
                    month = this.parseMonth(line);
                else
                    month = LocalDate.now().toString().substring(0, 7); // 默认当月
            } else if (line.startsWith("## ")) {
                day = true;
                list.add(line);
            } else if (day) {
                if (line.equals("---")) {
                    dayNotes.add(ParseDayNote.parseDayNote(list));
                    day = false;
                    list.clear();
                } else {
                    list.add(line);
                }
            }
        }
        dayNotes.add(ParseDayNote.parseDayNote(list));
        br.close();
        return new MonthNoteVo(month, dayNotes);
    }


    private String parseMonth(String str) {
        String temp = str.substring(1).trim();
        if (temp.length() < 3)
            str = "# " + LocalDate.now().getYear() + "-" + temp; // 默认当年
        String month = ParseDayNote.parseValue(str, ".*?(\\d{4}\\-\\d{2})", "月份格式不对：");
        log.debug("month: {}", month);
        return month;
    }

}
